<template>
	<view class="universal-detail">
		<view class="universal-detail-top">
			<view class="universal-detail-top-time">
				<text class="universal-detail-top-title">处理</text>
			</view>
		</view>

		<view class="univers al-detail-cont">
			<van-form class="universal-detail-form" @submit="onSubmit" label-width="170rpx">
				<van-cell-group>
					<van-field v-model="form.repairResult" required colon rows="4" autosize type="textarea"
						label="处理方式及结果" show-word-limit maxlength="200"
						:rules="[{ required: true, message: '请输入处理方式及结果' }]" placeholder="请输入处理方式及结果" />
					<van-field name="uploader" required colon :label="_typeName + '后照片'"
						:rules="[{ required: true, message: `请上传${_typeName}后照片` }]">
						<template #input>
							<upload-file accept="image/*" v-model="form.imageUrl"></upload-file>
						</template>
					</van-field>
					<van-field name="uploader" colon :label="_typeName + '后视频'">
						<template #input>
							<upload-file accept="video/*" v-model="form.videoUrl"></upload-file>
						</template>
					</van-field>
					<!-- 审核人 -->
					<van-field v-model="form.auditerName" is-link readonly required name="picker" label="审核人"
						placeholder="请选择审核人" @click="selectShow.user = true"
						:rules="[{ required: true, message: '请选择审核人' }]" />
				</van-cell-group>

				<van-cell :title="_typeName + '部位'">
					<template #right-icon>
						<van-button icon="plus" type="primary" size="small" @click="addMaintenanceParts">增加</van-button>
					</template>
				</van-cell>

				<van-cell-group v-for="(item, index) in form.parts" :key="item.id">
					<van-field :label="_typeName + '设备'" v-model="item.repairEquipmentName" is-link readonly colon
						placeholder="请选择设备" @click="openDialogDevice(index)" />
					<van-field :label="_typeName + '部位'" v-model="item.repairPart" type="input" colon show-word-limit
						maxlength="100" :placeholder="'请输入' + _typeName + '部位'" />
					<van-field v-model="item.repairContent" required colon rows="2" autosize type="textarea"
						:label="_typeName + '内容'" show-word-limit maxlength="200"
						:rules="[{ required: true, message: '请输入内容' }]" :placeholder="'请输入' + _typeName + '内容'" />
					<view style="padding: 0 50rpx 20rpx;">
						<van-button icon="delete" type="danger" size="small" block
							@click="deleteCurrent(index)">删除</van-button>
					</view>
				</van-cell-group>

				<view class="universal-detail-bottom">
					<van-button class="universal-detail-bottom-button universal-detail-bottom-button-cancel"
						type="default" @click="routeBack">取消</van-button>
					<van-button class="universal-detail-bottom-button universal-detail-bottom-button-sumbit"
						type="primary" native-type="submit">提交</van-button>
				</view>
			</van-form>
		</view>

		<!-- 选择器 单选 设备 -->
		<picker-search v-model:show="selectShow.device" :columns="devicesList" @confirm="onDeviceConfirm"
			@cancel="selectShow.device = false" />

		<!-- 选择器 审核人 -->
		<picker-search v-model:show="selectShow.user" :columns="usersList" @confirm="onUserConfirm"
			@cancel="selectShow.user = false"></picker-search>
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';

	import dayjs from 'dayjs';

	import {
		apiDevicesList,
		apiUsersList
	} from '@/api/common';

	import {
		apiDailyRepairSubmit
	} from '@/api/dailyFix';

	const model = defineModel();
	const emit = defineEmits(['confirm']);
	const form = ref({
		imageUrl: [],
		videoUrl: [],
		parts: [],
	});

	const _typeName = computed(() => {
		const typeMap = {
			1: '维修',
			2: '养护',
		};
		return typeMap[model.value.type?.value] || '';
	});

	const selectShow = ref({
		device: false,
		user: false,
	});
	let usersList = ref([]);

	// 设备列表
	let currentDeviceIndex = -1;
	const devicesList = ref([]);
	const getDevicesList = (param) => {
		apiDevicesList({
			// projectItemId
			deviceType: ''
		}).then(res => {
			devicesList.value = res.map(n => ({
				name: n.deviceName,
				value: n.deviceItemId,
				text: `${n.deviceName}-${n.sensorNo || ''}`,
			}));
		})
	}
	const openDialogDevice = (index) => {
		currentDeviceIndex = index;
		selectShow.value.device = true;
	}
	const onDeviceConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		form.value.parts[currentDeviceIndex].repairEquipment = selectedOptions[0].value;
		form.value.parts[currentDeviceIndex].repairEquipmentName = selectedOptions[0].text;
		console.log(currentDeviceIndex, form.value.parts)
		selectShow.value.device = false;
	}

	// 增加部位
	const addMaintenanceParts = () => {
		form.value.parts.unshift({
			id: new Date().getTime(),
			dailyRepairId: form.value.dailyRepairId,
			repairEquipment: '',
			repairPart: '',
			repairContent: '',
		});
	};
	// 删除部位
	const deleteCurrent = (index) => {
		form.value.parts.splice(index, 1);
	};
	// 验证部位
	const validateParts = () => {
		const value = form.value.parts;
		if (!value || value.length === 0) {
			uni.showToast({
				title: `至少添加一个${_typeName.value}部位`,
				icon: 'none',
			})
			return false;
		} else {
			for (let i = 0; i < value.length; i++) {
				const part = value[i];
				if (!part.repairEquipment || !part.repairPart || !part.repairContent) {
					uni.showToast({
						title: `请完善${_typeName}部位信息`,
						icon: 'none',
					})
					return false;
				}
			}
			return true;
		}
	};

	const onSubmit = () => {
		// if (!validateParts()) return;

		const param = {
			...form.value,
			finishPic: [...form.value.imageUrl, ...(form.value.videoUrl || [])],
			finishTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		}

		uni.showLoading({
			title: '提交中',
			mask: true
		});

		apiDailyRepairSubmit(param).then(res => {
			uni.showToast({
				title: '提交成功',
				icon: 'success',
			});
			emit('confirm');
		}).finally(() => {
			uni.hideLoading();
		})
	}

	// 选择器 审核人
	const onUserConfirm = ({
		selectedValues,
		selectedOptions
	}) => {
		form.value.auditer = selectedOptions[0].value;
		form.value.auditerName = selectedOptions[0].text;
		selectShow.value.user = false;
	}

	// 获取数据 人员
	const getUsersList = () => {
		apiUsersList({
			pageNumber: 1,
			pageSize: 10000,
		}).then(res => {
			usersList.value = res.records.map(n => ({
				text: n.name,
				value: n.userId
			}));
		})
	}
	getUsersList();

	const routeBack = () => {
		uni.navigateBack({
			delta: 1
		});
	}

	form.value.dailyRepairId = model.value.dailyRepairId || '';
	getDevicesList();
	addMaintenanceParts();
</script>

<style lang="scss" scoped>
	@import '@/assets/universal-detail.scss';
	@import '@/assets/form.scss';
</style>